import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

class Networks extends JFrame {
    Networks(final MQTT mqtt){
        JPanel jPanel1 = new JPanel();
        JLabel jLabel_ip = new JLabel("服务器IP地址：");
        final JTextField jTextField_ip = new JTextField(10);
        jTextField_ip.setText(mqtt.getIp());
        jPanel1.add(jLabel_ip);
        jPanel1.add(jTextField_ip);

        JPanel jPanel2 = new JPanel();
        JLabel jLabel_port = new JLabel("服务器端口号：");
        final JTextField jTextField_port = new JTextField(5);
        jTextField_port.setText(mqtt.getPort()+"");
        jPanel2.add(jLabel_port);
        jPanel2.add(jTextField_port);

        JPanel jPanel3 = new JPanel();
        JLabel jLabel = new JLabel("连接状态：");
        final JLabel jLabel_state = new JLabel("未连接！");
        jLabel_state.setForeground(Color.RED);
        jPanel3.add(jLabel);
        jPanel3.add(jLabel_state);

        final JButton jButton = new JButton();
        jButton.setText("连接");
        jButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                if(jButton.getText().equals("连接")) {
                    if (mqtt.connect(jTextField_ip.getText(), Integer.parseInt(jTextField_port.getText()))) {
                        jLabel_state.setText("已连接！");
                        jLabel_state.setForeground(Color.GREEN);
                        jButton.setText("断开");
                    }else
                        JOptionPane.showMessageDialog(null,"连接服务器失败！","错误",JOptionPane.ERROR_MESSAGE);
                }else{ //断开
                    if(mqtt.disconnect()) {
                        jLabel_state.setText("未连接！");
                        jLabel_state.setForeground(Color.RED);
                        jButton.setText("连接");
                        JOptionPane.showMessageDialog(null, "断开服务器成功！", "提示", JOptionPane.INFORMATION_MESSAGE);
                    }else
                        JOptionPane.showMessageDialog(null,"断开服务器失败！","错误",JOptionPane.ERROR_MESSAGE);
                }
            }
        });

        if(mqtt.getState()) {
            jLabel_state.setText("已连接！");
            jLabel_state.setForeground(Color.GREEN);
            jButton.setText("断开");
        }

        this.setLayout(new GridLayout(4,1));
        this.add(jPanel1);
        this.add(jPanel2);
        this.add(jPanel3);
        this.add(jButton);
        this.setTitle("网络设置");
        this.setSize(300,150);
        this.setVisible(true);
    }
}
